package cn.mandifal.user.controller;

import cn.mandifal.order.service.OrderService;
import cn.mandifal.pay.service.ZhiFuBaoPayService;
import cn.mandifal.pojo.DpPayLogs;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 支付控制层
 * @author shun
 */
@Controller
@RequestMapping("/zhiFuBaoPayController")
public class ZhiFuBaoPayController {
	
	@Reference
	private ZhiFuBaoPayService zhiFuBaoPayService;
	
	@Reference
	private OrderService orderService;

	/**
	 * 支付
	 * @param response 相应数据
	 * @param out_trade_no 支付订单号
	 * @throws Exception
	 */
	@RequestMapping("/pay")
	public void pay(HttpServletResponse response,String out_trade_no) throws Exception {
		//得到当前登录用户名
		String key="pay"+"-"+out_trade_no;
		//从缓存中得到支付日志
		DpPayLogs dpPayLogs = orderService.searchDpPayLogFromRedis(key);
		//如果不为空则扫码支付
		if (dpPayLogs!=null){
			//得到支付订单号
			String outTradeNo = dpPayLogs.getOutTradeNo();
			//得到支付总金额
			Long totalAmount = dpPayLogs.getTotalFee();

			response.addHeader("Access-Control-Allow-Origin", "*");
			response.addHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
			//不加这个响应头，有的浏览器不解析
			response.addHeader("Content-Type","text/html");
			String head="<html><head><meta http-equiv='Content-Type' content='text/html; charset=utf-8'></head>";
			String result = zhiFuBaoPayService.pay(outTradeNo, totalAmount+"");
			String buttom="<body></body></html>";
			response.getWriter().println(head+result+buttom);
		}else {
			//error 为 1 表示订单超时
			//为空重定向到失败页面
			response.sendRedirect("http://localhost:8087/payfail.html#?error=1");
		}
	}
	/**
	 * 同步调用成功后执行的操作
	 * @param request 用于获取付宝返回的参数
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/returnUrl")
	public void returnUrl(HttpServletRequest request, HttpServletResponse response) throws Exception{
		System.out.println("调用同步调用方法");
		Map map=new HashMap();
		//获得支付宝返回的参数
		Map<String,String[]> requestParams = request.getParameterMap();
		//验证签名
		Boolean signVerified = zhiFuBaoPayService.checkSign(requestParams);
		//是否通过验证
			if(signVerified) {
				//商户订单号
				String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
				//支付宝交易号
				String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
				//付款金额
				String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");
				response.sendRedirect("/paysuccess.html#?id="+out_trade_no+"&money="+total_amount+"&trade_no="+trade_no);

			}else {
			request.setAttribute("error","支付失败");
			request.getRequestDispatcher("/payfail.html").forward(request,response);
		}
	}

	/**
	 * 异步调用成功后执行的操作
	 * @param request 用于获取付宝返回的参数
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/notifyUrl")
	public void notifyUrl(HttpServletRequest request, HttpServletResponse response) throws Exception {
		System.out.println("调用异步调用方法");
		//获得支付宝返回的参数
		Map<String,String[]> requestParams = request.getParameterMap();
		//验证签名
		Boolean signVerified = zhiFuBaoPayService.checkSign(requestParams);
		//验证成功
		if(signVerified) {
			//商户订单号
			String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
			System.out.println(out_trade_no);
			//支付宝交易号
			String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

			//交易状态
			String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");

			if(trade_status.equals("TRADE_FINISHED")){
				System.out.println("TRADE_FINISHED");
				//判断该笔订单是否在商户网站中已经做过处理
				//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
				//如果有做过处理，不执行商户的业务程序
				//注意：
				//退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
			}else if (trade_status.equals("TRADE_SUCCESS")){
				System.out.println("TRADE_SUCCESS");
				//支付成功,更新订单相关表的状态，删除redis中的支付订单实体
				orderService.updateOrderStatus(out_trade_no,trade_no,"1");

				System.out.println("修改状态成功");
			}

			response.getWriter().println("success");
		}else {
			//验证失败
			response.getWriter().println("fail");

			//调试用，写文本函数记录程序运行情况是否正常
			//String sWord = AlipaySignature.getSignCheckContentV1(params);
			//AlipayConfig.logResult(sWord);
		}
	}
	@RequestMapping("/queryPay")
	public void queryPay(String out_trade_no, String trade_no) throws Exception {
		String result = zhiFuBaoPayService.queryPay(out_trade_no, trade_no);
		System.out.println(result);
	}
}
